package dolphin.mt521.cam.ac.uk;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Environment;
import android.util.Log;

public class Output {

    static float sampleRate = Encode.getSampleRate();
    
    public static void play(byte[] sineWave) {
        try {
            int minBufferSize = AudioTrack.getMinBufferSize(16000, 
                    AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT);
            AudioTrack audioTrack = new  AudioTrack(AudioManager.STREAM_MUSIC,
                                        16000,
                                        AudioFormat.CHANNEL_CONFIGURATION_MONO,
                                        AudioFormat.ENCODING_PCM_16BIT,
                                        minBufferSize,
                                        AudioTrack.MODE_STREAM);
            audioTrack.play();
            audioTrack.write(sineWave,0,sineWave.length);
            audioTrack.stop();
            audioTrack.release();
        }
        catch (Exception e) {
            Log.e("Output","Playback Failed");
        }
    }
    
    public static void saveFile(byte[] data, String filename) {
        File file = new File(Environment.getExternalStorageDirectory(), filename+MainActivity.count+".txt");
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            out.write(data,0,data.length);
            out.flush();
            out.close();
            Log.i("Output.saveFile","Save successful");
        }
        catch (IOException e) {
            Log.e("Output.saveFile","Save unsuccessful");
        }
    }

}
